package com.ts.manager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;

import com.rio.core.L;
import com.rio.core.S;
import com.rio.core.U;
import com.rio.helper.MD5Maker;
import com.rio.helper.PreferenceHelper;
import com.rio.helper.Sleeper;
import com.rio.helper.json.G;
import com.rio.layout.TaskManager;
import com.rio.layout.view.SimpleTask;
import com.ts.data.Machine;
import com.ts.host.APP;
import com.ts.host.Event;
import com.ts.host.N;
import com.ts.host.T;

import de.greenrobot.event.EventBus;

public class MachineManager {

	private PreferenceHelper mHelper;

	private Machine mMachine;

	private static MachineManager mInstance;
	

	public static MachineManager getInstance() {
		if (U.isNull(mInstance)) {
			mInstance = new MachineManager();
		}
		return mInstance;
	}

	public void destory() {
		mInstance = null;
		mHelper = null;
		mMachine = null;
	}

	public boolean isConnected() {
		return U.notNull(MachineManager.getInstance().getMachine().machinecode);
	}
	
	public  void killProcess() {

		PackageManager packageManager = APP.getContext().getPackageManager();
		Intent intent = packageManager
				.getLaunchIntentForPackage(APP.getContext().getPackageName());
		PendingIntent restartIntent = PendingIntent.getActivity(
				APP.getContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
//		// 退出程序
		AlarmManager mgr = (AlarmManager) APP.getContext()
				.getSystemService(Context.ALARM_SERVICE);
		mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 3000,
				restartIntent); // 1秒钟后重启应用
		android.os.Process.killProcess(android.os.Process.myPid());
		ActivityManager am = (ActivityManager) APP.getContext()
				.getSystemService(Context.ACTIVITY_SERVICE);
		am.restartPackage(APP.getContext().getPackageName());
		System.gc();
		System.exit(0);
	}
	
	public  void killProcess(int pid) {

		closeLedAndWater();
		PackageManager packageManager = APP.getContext().getPackageManager();
		Intent intent = packageManager
				.getLaunchIntentForPackage(APP.getContext().getPackageName());
		PendingIntent restartIntent = PendingIntent.getActivity(
				APP.getContext(), 0, intent, Intent.FLAG_ACTIVITY_CLEAR_TASK);
//		// 退出程序
		AlarmManager mgr = (AlarmManager) APP.getContext()
				.getSystemService(Context.ALARM_SERVICE);
		mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000,
				restartIntent); // 1秒钟后重启应用
		android.os.Process.killProcess(pid);
//		ActivityManager am = (ActivityManager) APP.getContext()
//				.getSystemService(Context.ACTIVITY_SERVICE);
//		am.restartPackage(APP.getContext().getPackageName());
		System.gc();
		System.exit(0);

	}
	

	/**
	 * 获取当前网络类型
	 * 
	 * @return 0：没有网络 1：WIFI网络 2：WAP网络 3：NET网络
	 */

	public static final int NETTYPE_WIFI = 0x01;
	public static final int NETTYPE_CMWAP = 0x02;
	public static final int NETTYPE_CMNET = 0x03;

	public String getNetworkType() {
		String netType = "有线网络";
		ConnectivityManager connectivityManager = (ConnectivityManager) APP
				.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return "没有网络";
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			String extraInfo = networkInfo.getExtraInfo();
			if (!TextUtils.isEmpty(extraInfo)) {
				if (extraInfo.toLowerCase().equals("cmnet")) {
					netType = "NET网络";
				} else {
					netType = "WAP网络";
				}
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = "WIFI网络";
		}
		return netType;
	}

	/**
	 * 获取版本号
	 * 
	 * @return
	 */
	public String getVersionCode() {
		PackageInfo info = null;
		try {
			info = APP.getContext().getPackageManager()
					.getPackageInfo(APP.getContext().getPackageName(), 0);
		} catch (NameNotFoundException e) {
			L.e(e);
		}
		if (U.notNull(info)) {
			return info.versionName;
		}
		return null;

	}
	
	public static String getLocalIpAddress()  
    {  
        try  
        {  
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)  
            {  
               NetworkInterface intf = en.nextElement();  
               for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)  
               {  
                   InetAddress inetAddress = enumIpAddr.nextElement();  
                   if (!inetAddress.isLoopbackAddress())  
                   {  
                       return inetAddress.getHostAddress().toString();  
                   }  
               }  
           }  
        }  
        catch (SocketException ex)  
        {  

        }  
        return null;  
    }  
	
	public static String getLocalMacAddressFromIp(Context context) {
        String mac_s= "";
       try {
            byte[] mac;
            NetworkInterface ne=NetworkInterface.getByInetAddress(InetAddress.getByName(getLocalIpAddress()));
            mac = ne.getHardwareAddress();
            mac_s = byte2hex(mac);
       } catch (Exception e) {
           e.printStackTrace();
       }
       
        return mac_s;
    }
    
    public static  String byte2hex(byte[] b) {
         StringBuffer hs = new StringBuffer(b.length);
         String stmp = "";
         int len = b.length;
         for (int n = 0; n < len; n++) {
          stmp = Integer.toHexString(b[n] & 0xFF);
          if (stmp.length() == 1)
           hs = hs.append("0").append(stmp);
          else {
           hs = hs.append(stmp);
          }
         }
         return String.valueOf(hs);
        }
    
	/**
	 * @return
	 */
	public String getLocalMacAddress() {
		return getLocalMacAddressFromIp(APP.getContext());
	}

	public void closeLedAndWater() {
		N.closeAll();
	}

	public void openLedAndWater() {
		N.openAll();
	}

	public void closeColdLed() {
		N.closeColdLed();
	}

	public void openColdLed() {
		N.openColdLed();
	}

	public void closeWarmLed() {
		N.closeWarmLed();
	}

	public void openWarmLed() {
		N.openWarmLed();
	}

	public void closeColdWater() {
		N.closeColdWater();
	}

	public void openColdWater() {
		N.openColdWater();
	}

	public void closeWarmWater() {
		N.closeWarmWater();
	}

	public void openWarmWater() {
		N.openWarmWater();
	}

	private PreferenceHelper getHelper() {
		if (U.isNull(mHelper))
			mHelper = PreferenceHelper.create(APP.getContext());
		return mHelper;
	}

	public String getPreference(String key, String defaultValue) {
		return getHelper().getString(key, defaultValue);
	}

	public String getPreference(String key) {
		return getPreference(key, S.EMPTY);
	}

	public void setPreference(String key, String value) {
		getHelper().putString(key, value);
	}

	private static final String KEY_MACHINE = "KEY_MACHINE";

	public String getMachineContent() {
		return getHelper().getString(KEY_MACHINE, S.EMPTY);
	}

	public Machine getMachine() {
		if (U.isNull(mMachine)) {
			String s = getHelper().getString(KEY_MACHINE, S.EMPTY);
			mMachine = G.toObject(s, Machine.class);
		}
		if (U.isNull(mMachine)) {
			mMachine = new Machine();
		}
		return mMachine;
	}

	public void setMachine(Machine machine) {
		if (U.notNull(machine)) {
			//对象一定要有汉字
			if(U.isNull(machine.address)){
				machine.address = "未知";
			}
			getHelper().putString(KEY_MACHINE, G.toJson(machine));
			mMachine = machine;
			EventBus.getDefault().post(new Event.GetAddress());
		}
	}
	
	public void unregister(){
		getHelper().putString(KEY_MACHINE, S.EMPTY);
		mMachine = null;
		
	}

	/******** 设备唯一号 *********/

	private static final String KEY_DEVICE_TOKEN = "KEY_DEVICE_TOKEN";

	private String mDeviceToken;

	/**
	 * 获取设备唯一号 获取Device Token的代码需要放在mPushAgent.enable();后面
	 * 
	 * @return
	 */
	public String getDeviceToken() {

		if (U.isNull(mDeviceToken)) {
			mDeviceToken = getHelper().getString(KEY_DEVICE_TOKEN, S.EMPTY);

			if (U.isNull(mDeviceToken)) {
				// 用友盟SDK生成
				// mDeviceToken = UmengRegistrar.getRegistrationId(APP
				// .getContext());
				// mDeviceToken = UUID.randomUUID().toString();
				mDeviceToken = MD5Maker.encode(MachineManager.getInstance()
						.getLocalMacAddress().getBytes());
				getHelper().putString(KEY_DEVICE_TOKEN, mDeviceToken);
			}
		}

		return mDeviceToken;
	}

	
	/******** 广告版本 *********/

	private static final String KEY_DATE = "KEY_DATE";

	private String mDateKey;

	/**
	 * @return
	 */
	public String getDateKey() {

		if (U.isNull(mDateKey)) {
			mDateKey = getHelper().getString(KEY_DATE, S.EMPTY);
		}
		return mDateKey;
	}
	
	public void setDateKey(String key){
			mDateKey = key;
			getHelper().putString(KEY_DATE, key);
		
	}
	
	public boolean compareDateKey(String key){
			long current = getData(key);
			long last  = getData(getDateKey());
			if(last < current){
				return true;
			}
			return false;
	}
	
	
	public static long getData(String key) {
		if(U.notNull(key)){
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
			Date date;
			try {
				date = formatter.parse(key);
				if(U.notNull(date)){
					return date.getTime();
				}
			} catch (ParseException e) {
				L.e(e);
			}
			return 0;			
		}else{
			return 0;
		}
	}

}
